<template>
    <view>
        <u-notice-bar text="关闭本页面将自动保存未提交的表单,下次打开此页面自动恢复内容." icon="-"></u-notice-bar>
        <!-- 车牌号选择按钮 -->
        <view class="cell-1">
            <view class="tit-1">
                <text>卸货车辆</text>
                <text class="del-btn yticon icon-iconfontshanchu1" @click="plateClearModel = true"></text>
            </view>
            <view class="content-1">
                <view class="plate-selection">
                    <view v-for="(plate, index) in plates" :key="index"
                        :class="['plate-button', { active: selectedPlate === plate }]"
                        @click="selectPlate(plate, index)">
                        {{ plate }}
                    </view>
                    <view class="plate-button plate-add-btn" @click="addPlateModel = true">
                        +
                    </view>
                </view>
            </view>
        </view>


        <!-- 凭据信息表单 -->
        <view class="cell-1">
            <view class="tit-1">
                车辆凭据
            </view>
            <view class="content-1">
                <view class="form-section" v-if="currFormIndex >= 0">
                    <u-form>
                        <!-- <u-form-item label="订单ID">
                            <u-input v-model="formData[currFormIndex].orderId" readonly></u-input>
                        </u-form-item>

                        <u-form-item label="小组ID">
                            <u-input v-model="formData[currFormIndex].groupId" readonly></u-input>
                        </u-form-item> -->

                        <u-form-item label="入场单据号">
                            <u-input v-model="formData[currFormIndex].accessSn"></u-input>
                        </u-form-item>

                        <u-form-item label="入场时间">
                            <text class="date-time"
                                @click="datetimePicker = true">{{`${formData[currFormIndex].accessTime?formData[currFormIndex].accessTime:'点击选择'}`}}</text>
                            <u-datetime-picker ref="datetimePicker" :show="datetimePicker"
                                v-model="formData[currFormIndex].accessTimestamp" mode="datetime"
                                @cancel='datetimePicker = false' @confirm="datetimeConfirm"
                                :formatter="datetimeFormatter"></u-datetime-picker>
                        </u-form-item>

                        <u-form-item label="商户编号">
                            <u-input v-model="formData[currFormIndex].shopSn"></u-input>
                        </u-form-item>

                        <u-form-item label="商户姓名">
                            <u-input v-model="formData[currFormIndex].shopOwner"></u-input>
                        </u-form-item>

                        <u-form-item label="车牌号">
                            <u-input v-model="formData[currFormIndex].trunkLicense" readonly></u-input>
                        </u-form-item>

                        <u-form-item label="车辆毛重">
                            <u-input v-model="formData[currFormIndex].grossWeight" type="number" placeholder="输入毛重"
                                @input="convertToGrams('grossWeight')">
                                <u-text text="kg" slot="suffix" margin="0 0 0 3px" type="tips"></u-text>
                            </u-input>
                        </u-form-item>

                        <u-form-item label="车辆皮重">
                            <u-input v-model="formData[currFormIndex].tareWeight" type="number" placeholder="输入皮重"
                                @input="convertToGrams('tareWeight')">
                                <u--text text="kg" slot="suffix" margin="0 0 0 3px" type="tips"></u--text>
                            </u-input>
                        </u-form-item>

                        <u-form-item label="货物净重">
                            <u-input v-model="formData[currFormIndex].goodWeight" type="number" placeholder="输入净重"
                                @input="convertToGrams('goodWeight')">
                                <u--text text="kg" slot="suffix" margin="0 0 0 3px" type="tips"></u--text>
                            </u-input>
                        </u-form-item>

                        <u-form-item label="装货类型">
                            <u-radio-group v-model="formData[currFormIndex].goodType">
                                <u-radio :value="0">单独装货</u-radio>
                                <u-radio :value="1">拼车装货</u-radio>
                            </u-radio-group>
                        </u-form-item>

                        <u-form-item label="凭证图片">
                            <u-upload :fileList="formData[currFormIndex].picsModel" @afterRead="afterReadCert"
                                @delete="deleteCert" name="pics" multiple :maxCount="5"></u-upload>
                        </u-form-item>

                        <!-- 货品集合 -->
                        <u-form-item label="货品">
                            <view v-for="(prod, index) in formData[currFormIndex].prods" :key="index">
                                <u-input v-model="prod.prodId" readonly></u-input>
                                <u-input v-model="prod.prodName" readonly></u-input>
                                <u-input v-model="prod.prodWeight" type="number" placeholder="输入货物重量 (kg)"
                                    @input="convertProdWeight(index)"></u-input>
                            </view>
                        </u-form-item>

                        <!-- 订单额外费用 -->
                        <!-- <u-form-item label="订单额外费用">
                            <u-input v-model="extraFee" type="number" placeholder="请输入金额"></u-input>
                        </u-form-item> -->
                    </u-form>
                </view>
            </view>
        </view>

        <TrailerKeyboard :show.sync="addPlateModel" :vehicleNo="newPlate" @confirm="addPlate" vehicleType="car">
        </TrailerKeyboard>

        <!-- <u-modal :show="pageBackModel" title="保存凭证" content='检测到您还有未提交的信息,是否临时保存此页面,下次打开将恢复未提交的数据' showCancelButton
            @confirm="savePageBack(1)" @cancel="savePageBack(0)">
            <u-button slot="confirmButton" text="确定" type="success" shape="square" @click="show8 = false">
            </u-button>
        </u-modal> -->
        <u-modal :show="plateClearModel" title="清空车辆" content='是否要清空已填写的全部车辆？' showCancelButton @confirm="plateClear"
            @cancel="plateClearModel = false">
        </u-modal>
    </view>
</template>

<script>
    import TrailerKeyboard from "@/components/car-board/carBoard.vue";
    import {
        imageApi,
        orderApi
    } from '@/api';
    export default {
        data() {
            return {
                datetimePicker: false,
                save_timer: null,
                orderId: 0,
                pageBackModel: false,
                plateClearModel: false,
                plates: [], // 初始车牌号列表
                selectedPlate: '', // 当前选择的车牌号
                addPlateModel: false,
                newPlate: '', // 新车牌输入框
                extraFee: 0, // 额外费用
                currFormIndex: -1,
                formData: [],
                formDataTemplate: {
                    orderId: '',
                    groupId: '',
                    accessSn: '',
                    accessTime: null,
                    accessTimestamp: null,
                    shopSn: '',
                    shopOwner: '',
                    trunkLicense: '',
                    grossWeight: null,
                    tareWeight: null,
                    goodWeight: null,
                    goodType: 0,
                    pics: [],
                    picsModel: [],
                    prods: []
                },
                order: {}
            };
        },
        components: {
            TrailerKeyboard
        },
        methods: {
            selectPlate(plate, index = -1) {
                if (index === -1) {
                    index = this.formData.length - 1;
                }
                this.selectedPlate = plate;
                this.currFormIndex = index;
                console.log(`index:${index},plate:${plate}`)
            },
            addPlate(plateInput) {
                if (plateInput) {
                    this.plates.push(plateInput);
                    const now = new Date();

                    // 深拷贝 this.formDataTemplate 并赋值给新的对象
                    const newFormData = JSON.parse(JSON.stringify(this.formDataTemplate));

                    // 设置新的对象的 trunkLicense 属性
                    newFormData.trunkLicense = plateInput;
                    newFormData.accessTime = this.formatDate(now);
                    newFormData.accessTimestamp = now.getTime();

                    // 将新的对象推入 formData 数组
                    this.formData.push(newFormData);

                    // 调用 selectPlate 方法，传入 plateInput 参数
                    this.selectPlate(plateInput);

                    console.log(this.formData);
                }
            },

            datetimeFormatter(type, value) {
                if (type === 'year') {
                    return `${value}年`
                }
                if (type === 'month') {
                    return `${value}月`
                }
                if (type === 'day') {
                    return `${value}日`
                }
                if (type === 'hour') {
                    return `${value}时`
                }
                if (type === 'minute') {
                    return `${value}分`
                }
                return value
            },
            datetimeConfirm(e) {
                const timeFormat = uni.$u.timeFormat;
                const timeFormated = timeFormat(e.value, 'yyyy-mm-dd hh:MM');
                console.log(timeFormated)
                this.formData[this.currFormIndex].accessTime = timeFormated;
                this.datetimePicker = false;
            },
            formatDate(date) {
                // 格式化日期为 'yyyy-mm-dd hh:MM'
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');

                return `${year}-${month}-${day} ${hours}:${minutes}`;
            },
            parseDateTime(datetimeStr) {
                // 使用正则表达式解析日期和时间部分
                const [datePart, timePart] = datetimeStr.split(' ');
                const [year, month, day] = datePart.split('-').map(Number);
                const [hours, minutes] = timePart.split(':').map(Number);

                // 创建 Date 对象，月份需要减 1 因为 JavaScript 的月份是从 0 开始的
                const date = new Date(year, month - 1, day, hours, minutes);

                // 返回时间戳
                return date.getTime();
            },

            afterReadCert(event) {
                this.handleUpload(event, 'pics');
            },
            deleteCert(event) {
                this.formData[this.currFormIndex].pics.splice(event.index, 1);
                this.formData[this.currFormIndex].picsModel.splice(event.index, 1);
            },
            async handleUpload(event, listName) {
                const files = [].concat(event.file);
                for (const file of files) {
                    const result = await imageApi.upload(file.url);
                    this.formData[this.currFormIndex][listName].push(result.data);
                    this.formData[this.currFormIndex]['picsModel'].push({
                        ...file,
                        status: 'success',
                        url: result.data,
                    });
                }
            },
            convertToGrams(field) {
                // if (this.formData[this.currFormIndex][field] !== null) {
                //     this.formData[this.currFormIndex][field] = parseFloat(this.formData[this.currFormIndex][field]) *
                //         1000;
                // }
            },

            convertProdWeight(index) {
                // const prod = this.formData[this.currFormIndex].prods[index];
                // if (prod.prodWeight !== null) {
                //     prod.prodWeight = parseFloat(prod.prodWeight) * 1000;
                // }
            },

            plateClear() {
                this.plates = [];
                this.selectedPlate = '';
                this.extraFee = 0;
                this.currFormIndex = -1;
                this.formData = [];

                this.plateClearModel = false;
            },

            async fetchOrder(orderId) {
                const {
                    code,
                    data
                } = await orderApi.getOrderById(orderId);
                if (code == 200) {
                    this.order = data;
                }
            },

            savePageBack() {
                if (this.formData.length == 0) {
                    this.delPageBack();
                    return;
                }
                const formTemp = {
                    orderId: this.orderId,
                    pageBackModel: this.pageBackModel,
                    plates: this.plates, // 初始车牌号列表
                    selectedPlate: this.selectedPlate, // 当前选择的车牌号
                    addPlateModel: this.addPlateModel,
                    newPlate: this.newPlate, // 新车牌输入框
                    extraFee: this.extraFee, // 额外费用
                    currFormIndex: this.currFormIndex,
                    formData: this.formData,
                    formDataTemplate: this.formDataTemplate,
                    order: this.order
                }
                uni.setStorageSync(`formData-${this.orderId}`, formTemp)
            },

            getPageBack() {
                const fromTemp = uni.getStorageSync(`formData-${this.orderId}`)
                console.log(fromTemp)
                if (fromTemp) {
                    this.orderId = fromTemp.orderId,
                        this.pageBackModel = fromTemp.pageBackModel,
                        this.plates = fromTemp.plates,
                        this.selectedPlate = fromTemp.selectedPlate,
                        this.addPlateModel = fromTemp.addPlateModel,
                        this.newPlate = fromTemp.newPlate,
                        this.extraFee = fromTemp.extraFee,
                        this.currFormIndex = fromTemp.currFormIndex,
                        this.formData = fromTemp.formData,
                        this.formDataTemplate = fromTemp.formDataTemplate,
                        this.order = fromTemp.order
                }
            },

            delPageBack() {
                uni.removeStorageSync(`formData-${this.orderId}`)
            }
        },
        onLoad(option) {
            this.fetchOrder(option.orderId);
            this.orderId = option.orderId
            this.getPageBack();
        },
        onUnload() {
            clearInterval(this.save_timer);
            this.savePageBack();
            // this.pageBackModel = true;
            return;
        },
        onReady() {
            this.$refs.datetimePicker.setFormatter(this.datetimeFormatter)
        },
        mounted() {
            this.save_timer = setInterval(() => {
                this.savePageBack();
            }, 1000)
        }
    };
</script>

<style lang="scss">
    .plate-selection {
        display: flex;
        flex-flow: wrap;
        margin-bottom: 16upx;
    }

    .plate-button {
        padding: 8upx 16upx;
        margin: 5px;
        border: 1upx solid #d9a1a1;
        border-radius: 4upx;
        cursor: pointer;
        background-color: #ffe6e6;
    }

    .plate-button.plate-add-btn {
        background-color: #ffeaea;
        color: #e63946;
        border-color: #e63946;
    }

    .plate-button.active {
        background-color: #e66973;
        color: white;
    }

    .form-section {

        .u-form-item__body__left {
            width: 175rpx !important;
            padding-left: 5px;
            background: #ffe7e79c;
            border: solid 1px #FBDBE1;
            border-right: 0;

            text {
                text-align-last: justify !important;
                display: inline !important;
            }
        }

        .u-form-item__body__right {
            padding-left: 5px;
            background: #ffffff;
            border: solid 1px #FBDBE1;
            border-left: 0;
            min-height: 40px;

            text {
                // text-align-last: justify !important;
                display: inline !important;
            }

            .u-picker__view__column {
                text {
                    // text-align-last: center !important;
                    display: block !important;
                }
            }
        }

    }

    .u-upload__button {
        margin: 8px 0 8px 8px !important;
    }

    .u-upload__wrap__preview {
        margin: 8px 0 8px 8px !important;
    }

    .u-notice-bar {
        background-color: #f1f1f1 !important;
    }

    .u-notice__content__text {
        text {
            color: #757575 !important;
        }
    }

    .u-notice__left-icon {
        display: none !important;
    }

    .cell-1 {
        margin: 50rpx 40rpx 0 40rpx;
        border-left: #ffb9bc 5px solid;
        background: #ffffff;

        .tit-1 {
            margin: 10rpx 0 0 5px;
            padding-top: 10rpx;
            color: #e08181;
            font-size: 15px;
            font-weight: 600;

            .del-btn {
                padding: 10upx 0 10upx 36upx;
                font-size: $font-lg;
                color: $font-color-light;
                position: relative;

                &:after {
                    content: '';
                    width: 0;
                    height: 30upx;
                    border-left: 1px solid $border-color-dark;
                    position: absolute;
                    left: 20upx;
                    top: 50%;
                    transform: translateY(-50%);
                }
            }
        }

        .content-1 {
            padding: 5px;
        }
    }
</style>